package com.samphanie.admin.security;

import com.samphanie.admin.modules.sys.service.ISysUserService;
import com.samphanie.mbg.model.sys.SysUser;
import com.samphanie.security.domain.SecurityUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

/**
 * 默认的 UserDetailsPasswordService 实现
 *
 * @author ZSY
 * @date 2021/11/9 10:37
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsPasswordServiceImpl implements UserDetailsPasswordService {


    private final ISysUserService userService;

    @Override
    public UserDetails updatePassword(UserDetails userDetails, String newPassword) {
        userService.updateUserPasswordById(userDetails.getUsername(), newPassword);
        SysUser user = userService.findUserByUsername(userDetails.getUsername())
                .orElseThrow(() -> new UsernameNotFoundException("Cannot find user"));
        return SecurityUser.builder()
                .id(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                .enabled(user.isEnabled())
                .accountNonExpired(user.isAccountNonExpired())
                .accountNonLocked(user.isAccountNonLocked())
                .credentialsNonExpired(user.isCredentialsNonExpired())
                .authorities(user.getRoles().stream()
                        .map(role -> new SimpleGrantedAuthority(role.getRoleName()))
                        .collect(Collectors.toSet())
                ).build();
    }
}
